import React from 'react';
import IceContainer from '@icedesign/container';
import {Button, Input, Message, Radio, Select} from '@alifd/next';
import {
    FormBinder as IceFormBinder,
    FormBinderWrapper as IceFormBinderWrapper,
    FormError as IceFormError,
} from '@icedesign/form-binder';
import styles from './index.module.scss';
import event from '@/request'
import $http from '@/service/Services';


const axios = $http;

const {Option} = Select;
const {Group: RadioGroup} = Radio;
let form;

const Shape = {
    NO: 'normal',
    OFF: 'button'
};
const ItemDirection = {
    HORIZON: 'hoz',
    VERTICAL: 'ver'
};

/**
 * list
 */
class BusinessIntelligenceChartAdd extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            typeConfig: {},
            value: {},
            schemaList: [],
            addValue: {},
            mockData: [],
            businessList: [],
            charTypes: [],
            change: false,
            arr: [{
                _id: Math.random().toString(36).substring(2),
                name: "",
                value: ""
            }],
            id: "",
            subjectId: "",
            addVisible: false,
            config: {
                data: null,
                visible: false,
                title: "",
                content: ""
            },
            placeholder: "请输入数据",
            shape: Shape.NO,
            itemDirection: ItemDirection.HORIZON
        };
        this.$http = $http;
        this.formChange = this.formChange.bind(this);
        this.validateAllFormField = this.validateAllFormField.bind(this);
    }

    /**
     * 在渲染前调用,在客户端也在服务端
     */
    componentWillMount = () => {
        const params = new URLSearchParams(this.props.location.search);
        const id = params.get("id");
        this.setState({
            id: id,
        }, () => {
            setTimeout(() => {
                this.getBusinessIntelligenceChartTypes();
            }, 0);
            setTimeout(() => {
                this.getBusinessList();
            }, 0);
            if (id) {
                const that = this;
                this.$http.get(event.event.url + '/v1/intelligenceChart/getBusinessIntelligenceChartById/' + id)
                    .then(function (response) {
                        const {data} = response;
                        if (data.code === 1) {
                            Message.warning(data.message ? data.message : data.data);
                        } else {
                            const arr = data.data.chartColumnsVOS.map(
                                o => {
                                    const id = Math.random().toString(36).substring(2);
                                    o["_id"] = id;
                                    o[id + "_columnName"] = o["columnName"];
                                    o[id + "_column"] = o["column"];
                                    o[id + "_columnType"] = o["columnType"];
                                    o[id + "_color"] = o["color"];
                                    return o;
                                }
                            );
                            that.setState({
                                value: data.data,
                                arr: arr
                            })
                        }
                    })
                    .catch(function (error) {
                        console.error(error);
                        Message.error(error.message);
                    })
            }
        });
    };

    /**
     * 根据id查询详情
     */
    getBusinessList = () => {
        const that = this;
        let urls = event.event.url + '/v1/platformBusiness/getPlatformBusinessList';
        this.$http.post(urls)
            .then(function (response) {
                const {data} = response;
                that.setState({
                    businessList: data.data
                })
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };

    /**
     * 根据id查询详情
     */
    getBusinessIntelligenceChartTypes = () => {
        const that = this;
        let urls = event.event.url + '/v1/intelligenceChartType/getBusinessIntelligenceChartTypes';
        this.$http.get(urls)
            .then(function (response) {
                const {data} = response;
                that.setState({
                    charTypes: data.data
                })
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };
    /**
     * 高级属性是否可用
     * @param checked
     */
    onChange = (checked) => {
        this.setState({
            change: checked
        })
    }

    /* 表改变
    * @param formValue
    */
    formChange = (formValue) => {
        this.setState({
            value: formValue
        })
    };


    /**
     * 表验证
     */
    validateAllFormField = () => {
        const that = this;
        const {arr} = this.state;
        form.validateAll((errors, values) => {
            values["chartColumnsVOS"] = arr;
            const urls = event.event.url + '/v1/intelligenceChart/saveOrUpdateChart';
            that.$http.post(urls, values)
                .then(function (response) {
                    const {data} = response;
                    if (data.code === 1) {
                        Message.warning(data.message ? data.message : data.data);
                    } else {
                        Message.success("操作成功.");
                        that.props.history.go(-1);
                    }
                })
                .catch(function (error) {
                    Message.error(error.message);
                })
        });
    };
    /**
     * 取消提示弹框
     */
    onCloseDialog = reason => {
        this.setState({
            visible: false
        });
    };

    /**
     * 新增参数
     */
    handleClickAdd = () => {
        const arr = this.state.arr;
        arr.push({
            _id: Math.random().toString(36).substring(2),
            columnName: "",
            column: "",
            columnType: "",
            color: ""
        });
        this.setState(
            {
                arr: arr
            }
        )
    };
    /**
     * 删除参数
     */
    deleteClick = (ob) => {
        const {arr} = this.state;
        for (let i = 0; i < arr.length; i++) {
            if (arr[i]["_id"] === ob["_id"]) {
                arr.splice(i, 1);
                break;
            }
        }
        this.setState(
            {
                arr: arr
            }
        );

    };


    /**
     *
     * @param value value: {String} 数据
     * @param event e_: {Event} DOM事件对象
     */
    changeColumnName = (value, event) => {
        const id = event.target.id;
        const {arr} = this.state;
        for (let i = 0; i < arr.length; i++) {
            if (arr[i]["_id"] === id) {
                arr[i]["columnName"] = value;
                arr[i][id + "_columnName"] = value;
            }
        }
        this.setState(
            {
                arr: arr
            }
        )
    };
    /**
     *
     * @param value value: {String} 数据
     * @param event e_: {Event} DOM事件对象
     */
    changeColumn = (value, event) => {
        const id = event.target.id;
        const {arr} = this.state;
        for (let i = 0; i < arr.length; i++) {
            if (arr[i]["_id"] === id) {
                arr[i]["column"] = value;
                arr[i][id + "_column"] = value;
            }
        }
        this.setState(
            {
                arr: arr
            }
        )
    };

    /**
     *
     * @param value value: {String} 数据
     * @param id e_: {Event} DOM事件对象
     */
    changeColumnType = (value, id) => {
        const {arr} = this.state;
        for (let i = 0; i < arr.length; i++) {
            if (arr[i]["_id"] === id) {
                arr[i]["columnType"] = value;
                arr[i][id + "_columnType"] = value;
            }
        }
        this.setState(
            {
                arr: arr
            }
        )
    };


    /**
     *
     * @param value value: {String} 数据
     * @param event e_: {Event} DOM事件对象
     */
    changeColor = (value, event) => {
        const id = event.target.id;
        const {arr} = this.state;
        for (let i = 0; i < arr.length; i++) {
            if (arr[i]["_id"] === id) {
                arr[i]["color"] = value;
                arr[i][id + "_color"] = value;
            }
        }
        this.setState(
            {
                arr: arr
            }
        )
    };

    /**
     * 表
     * @returns {*}
     */
    render() {
        const {arr} = this.state;
        return (
            <div>
                <div className='container-header'>
                    <p style={{display: 'inline-block'}}>{this.state.id ? "修改图例" : "新建图例"}</p>
                    <Button type="normal" size="small" className='next-btn-normal table-btn-return'
                            style={{float: 'right'}}>
                        <a onClick={() => {
                            this.props.history.go(-1)
                        }}> 返回</a>
                    </Button>
                </div>


                <IceContainer className='container-main'>
                    <IceFormBinderWrapper
                        value={this.state.value}
                        onChange={this.formChange}
                        ref={formRef => form = formRef}
                    >
                        <div className={styles.formContent}>
                            <h4 className={styles.dTitle}>基础信息</h4>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span className={styles.red}>*</span>业务：</div>
                                <IceFormBinder required name="businessId" message="业务不能为空">
                                    <Select
                                        placeholder="请选择"
                                        name="businessId"
                                        className={styles.inputNme}
                                    >
                                        {
                                            this.state.businessList.map(
                                                o => {
                                                    return (
                                                        <Option value={o.id}>{o.name}</Option>
                                                    )
                                                }
                                            )
                                        }
                                    </Select>
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="businessId"/>
                                </div>
                            </div>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span className={styles.red}>*</span>图例类型：</div>
                                <IceFormBinder required name="chartType" message="图例类型为空">
                                    <Select
                                        placeholder="请选择"
                                        name="chartType"
                                        className={styles.inputNme}
                                    >
                                        {
                                            this.state.charTypes.map(
                                                o => {
                                                    return (
                                                        <Option value={o.id}>{o.name}</Option>
                                                    )
                                                }
                                            )
                                        }
                                    </Select>
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="chartType"/>
                                </div>
                            </div>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span className={styles.red}>*</span>图例标题：</div>
                                <IceFormBinder
                                    required
                                    triggerType="onBlur"
                                    message=" 图例标题不能为空"
                                    name="title"
                                >
                                    <Input
                                        placeholder="请输入标题名称"
                                        className={styles.inputNme}
                                    />
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="title"/>
                                </div>
                            </div>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span className={styles.red}>*</span>表名：</div>
                                <IceFormBinder
                                    required
                                    triggerType="onBlur"
                                    message="表名不能为空"
                                    name="tableName"
                                >
                                    <Input
                                        placeholder="请输入表名"
                                        className={styles.inputNme}
                                    />
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="tableName"/>
                                </div>
                            </div>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span className={styles.red}>*</span>默认宽度：</div>
                                <IceFormBinder
                                    required
                                    triggerType="onBlur"
                                    message=" 默认宽度不能为空"
                                    name="defaultWidth"
                                >
                                    <Input
                                        placeholder="请输入默认宽度"
                                        className={styles.inputNme}
                                    />
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="defaultWidth"/>
                                </div>
                            </div>
                            <div className={styles.formItem}>
                                <div className={styles.formLabel}><span className={styles.red}>*</span>默认高度：</div>
                                <IceFormBinder
                                    required
                                    triggerType="onBlur"
                                    message=" 默认高度不能为空"
                                    name="defaultHeight"
                                >
                                    <Input
                                        placeholder="请输入默认高度"
                                        className={styles.inputNme}
                                    />
                                </IceFormBinder>
                                <div className={styles.formError}>
                                    <IceFormError name="defaultHeight"/>
                                </div>
                            </div>

                            <div className={styles.formItem}>
                                <div className={styles.formLabel}>图表配置:</div>
                                <IceFormBinder
                                    triggerType="onBlur"
                                    name="config"
                                >
                                    <Input.TextArea
                                        maxLength={50}
                                        rows={8}
                                        hasLimitHint
                                        placeholder="请输入描述"
                                        className={styles.inputNme}
                                    />
                                </IceFormBinder>
                            </div>

                            <div className={styles.formItem}>
                                <div className={styles.formLabel}>描述:</div>
                                <IceFormBinder
                                    triggerType="onBlur"
                                    name="content"
                                >
                                    <Input.TextArea
                                        maxLength={50}
                                        rows={8}
                                        hasLimitHint
                                        placeholder="请输入描述"
                                        className={styles.inputNme}
                                    />
                                </IceFormBinder>
                            </div>


                            <div>
                                <div className={styles.formContent}>
                                    <h4 className={styles.dTitle}>数据列</h4>
                                    <div className={styles.container} style={{marginTop: '0'}}>
                                        <div className={styles.buttons}>
                                            <Button
                                                className={styles.button}
                                                onClick={() => this.handleClickAdd()}
                                            >
                                                添加数据列
                                            </Button>
                                        </div>
                                    </div>
                                </div>
                                {
                                    this.state.arr.map(
                                        (o, index) => {
                                            return (
                                                <div id="addInput" className={styles.formItem}>
                                                    <div className={styles.formLabel}>数据列名称：</div>
                                                    <Input id={o._id}
                                                           value={o.columnName}
                                                           defaultValue={o.columnName}
                                                           placeholder={"请输入参数名称"} onChange={this.changeColumnName}
                                                           className={styles.inputKeyValueNme}
                                                    />
                                                    <div className={styles.formError}>
                                                        <IceFormError name="columnName"/>
                                                    </div>

                                                    <div className={styles.formLabel}> 数据列：</div>

                                                    <Input id={o._id}
                                                           value={o.column}
                                                           defaultValue={o.column}
                                                           onChange={this.changeColumn}
                                                           placeholder="请输入参数值"
                                                           className={styles.inputKeyValueNme}
                                                    />
                                                    <div className={styles.formError}>
                                                        <IceFormError name="column"/>
                                                    </div>


                                                    <div className={styles.formLabel}> 数据列类型：</div>
                                                    <Select id={o._id}
                                                            style={{
                                                                width: 100
                                                            }}
                                                            value={o.columnType}
                                                            onChange={(value => {
                                                                this.changeColumnType(value,o._id);
                                                            })}
                                                            defaultValue={o.columnType}
                                                            placeholder="请输入参数值"
                                                            className={styles.inputNme}
                                                    >
                                                        <Option value="String">字符</Option>
                                                        <Option value="Long">长整数</Option>
                                                        <Option value="Integer">整数</Option>
                                                        <Option value="Double">浮点数</Option>
                                                    </Select>
                                                    <div className={styles.formError}>
                                                        <IceFormError name="columnType"/>
                                                    </div>

                                                    <div className={styles.formLabel}> 配色：</div>

                                                    <Input id={o._id}
                                                           value={o.color}
                                                           defaultValue={o.color}
                                                           onChange={this.changeColor}
                                                           placeholder="请输入参数值"
                                                           className={styles.inputKeyValueNme}
                                                    />
                                                    <div className={styles.formError}>
                                                        <IceFormError name="color"/>
                                                    </div>
                                                    <Button type="normal" onClick={() => this.deleteClick(o)}
                                                            warning>删除</Button> &nbsp;&nbsp;
                                                </div>
                                            )
                                        }
                                )
                                }
                            </div>
                            <Button
                                type="primary"
                                className='sync-btn-submit'
                                onClick={this.validateAllFormField}
                            >
                                提 交
                            </Button> &nbsp;&nbsp;
                            <Button
                                type="primary"
                                className='zgph-btn-cancel'
                                onClick={() => {
                                    this.props.history.go(-1)
                                }}
                            >
                                取 消
                            </Button>
                        </div>
                    </IceFormBinderWrapper>
                </IceContainer>
            </div>
        );
    }

}

export default BusinessIntelligenceChartAdd;
